#include "UserList.h"
#include "LutController.h"

UserList::UserList(QObject *parent) :
		QAbstractListModel(parent)
{
	users = new QList<User*>();

}

QVariant UserList::data(const QModelIndex &index, int role) const
{
	if (!index.isValid())
		return QVariant();

	if (index.row() >= users->size())
		return QVariant();

	if (role == Qt::DisplayRole || role == Qt::EditRole)
		return users->at(index.row())->getName();

	if (role == Qt::UserRole)
		return users->at(index.row())->getId();

	if (role == Qt::ForegroundRole)
	{
		if(LutController::getInstance()->myId() == users->at(index.row())->getId())
			return Qt::darkRed;
		return Qt::darkBlue;
	}
	else
		return QVariant();
}

int UserList::rowCount(const QModelIndex &) const
{
	return users->size();
}

Qt::ItemFlags UserList::flags(const QModelIndex &index) const
{
	if (!index.isValid())
		return Qt::ItemIsEnabled;

	return QAbstractListModel::flags(index);
}

bool UserList::insertRow(int row, const QModelIndex &parent)
{
	beginInsertRows(parent, row, row);
	users->insert(row, new User(-1, ""));
	endInsertRows();
	return true;
}

bool UserList::removeRow(int row, const QModelIndex &parent)
{
	beginRemoveRows(parent, row, row);
	users->removeAt(row);
	endRemoveRows();
	return true;
}

bool UserList::setData(const QModelIndex &index, const QVariant &value, int role)
{
	if(index.isValid() && role == Qt::EditRole)
	{
		users->at(index.row())->setName(value.toString());
		emit dataChanged(index, index);
		return true;
	}
	else if(index.isValid() && role == Qt::UserRole)
	{
		users->at(index.row())->setId(value.toInt());
		emit dataChanged(index, index);
		return true;
	}
	else return false;
}

void UserList::addOrReplace(User *u)
{
	User *existing = 0;
	int i = 0;
	while(i<users->size() && !existing)
	{
		if(users->at(i)->getId() == u->getId())
		{
			existing = users->at(i);
			existing->setName(u->getName());
			emit dataChanged(index(0, 0), index(users->size()-1, 0));
		}
		i++;
	}
	if(!existing)
	{
		insertRow(users->size(), QModelIndex());
		setData(index(users->size()-1, 0), u->getId(), Qt::UserRole);
		setData(index(users->size()-1, 0), u->getName(), Qt::EditRole);
	}

}
void UserList::clear()
{
	users->clear();
	emit dataChanged(index(0, 0), index(users->size()-1, 0));
}

void UserList::removeRowById(int id)
{
	int i = 0;
	while(i<users->size())
	{
		if(users->at(i)->getId() == id)
		{
			users->removeAt(i);
			emit dataChanged(index(0, 0), index(users->size()-1, 0));
		}
		i++;
	}
}

QString UserList::getNameById(int id)
{
	int i = 0;
	while(i<users->size())
	{
		if(users->at(i)->getId() == id)
			return users->at(i)->getName();
		i++;
	}
	return "";
}

